package com.app.hmst.main;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.app.hmst.json.JSONParserForGetList;
import com.app.hmst.model.CategoryVO;
import com.app.hmst.model.HomestayInfoVO;
import com.app.hmst.model.HomestayVO;
import com.app.hmst.model.HouseInfoVO;
import com.app.hmst.model.IndicatorResultVO;
import com.app.hmst.model.IndicatorVO;
import com.app.hmst.model.SubCategoryVO;
import com.app.hmst.utils.GlobalVariable;
import com.app.hmst.utils.NumberUtils;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.roscopeco.ormdroid.Entity;

@SuppressLint({ "NewApi", "ValidFragment" }) public class ViewAllSummaryEvaluatePageFragment extends Fragment{
	private View v;
	private ImageView menuIcon,clickConfirm;
	private SlidingMenu _sm;
	private ListView evaluateListView;
	private TextView overAllScore,resultStr;
	private HomestayInfoVO homestayInfoVO;
	private double overall;
	private String condition;
	private int con1Err=0,con2Err=0;
	private int state = 0;
	
	public ViewAllSummaryEvaluatePageFragment(SlidingMenu sm, HomestayInfoVO temp){
		this._sm = sm;
		this.homestayInfoVO = temp;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		System.gc();
		
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		
		v = inflater.inflate(R.layout.fragment_view_all_summary_evaluate_page,container, false);
		menuIcon = (ImageView) v.findViewById(R.id.imageView6);
		clickConfirm = (ImageView) v.findViewById(R.id.button1);
		overAllScore = (TextView) v.findViewById(R.id.textView3);
		resultStr = (TextView) v.findViewById(R.id.textView4);
		List<IndicatorResultVO> indResultVOs = Entity
				.query(IndicatorResultVO.class)
				.where("homeId")
				.eq(homestayInfoVO.id)
				.and("houseId")
				.eq("0")
				.and("indicatorId")
				.in("select indicatorId From comapphmstmodelIndicatorResultVO ")
				.executeMulti();

		HomestayVO vo = new HomestayVO();
		HomestayVO homestayVO = Entity.query(HomestayVO.class).where("type").eq(GlobalVariable.TYPE_HOMESTAY).execute();
		if (indResultVOs == null|| indResultVOs.size() != vo.getFormSize(homestayVO)) {
			//clickConfirm.setVisibility(View.GONE);
			clickConfirm.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.confirm_to_save_from_show_all_disable));
			state=0;
		} else {
			//clickConfirm.setVisibility(View.VISIBLE);
			clickConfirm.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.confirm_to_save_from_show_all));
			state=1;
		}
		
		clickConfirm.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(state==1){
					if(isNetworkAvailable()){
						AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
			            builder1.setMessage(getString(R.string.connection_refuse));
			            builder1.setCancelable(true);
			            builder1.setPositiveButton(getString(R.string.try_again_txt),new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int id) {
			                    dialog.cancel();
			                    actionSending();
			                }
			            });
			            builder1.setNegativeButton(getString(R.string.cancel_message),new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int id) {
			                    dialog.cancel();
			                }
			            });
			            AlertDialog alert11 = builder1.create();
			            alert11.show();	     
					}else{
						actionSending();
					}
				}
				
				
			}
		});
		evaluateListView = (ListView) v.findViewById(R.id.listView1);
		new InitAndLoadSubList().execute();
		menuIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				_sm.toggle();
			}
		});
		
		new Utils(getActivity()).onBackPressed(v, new ViewAllEvaluatePageFragment(_sm),null);
		return v;
	}
  
    public class AllEvaluateMenuAdapter extends BaseAdapter{
    	public List<TempSummary> evaluateList;
    	public ViewHolder viewHolder;
    	
    	public AllEvaluateMenuAdapter(List<TempSummary> evaluateList){
    		this.evaluateList=evaluateList;
    	}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return evaluateList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return evaluateList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final TempSummary temp;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.each_summary_evaluate_list,null);
				viewHolder.textShowPercProgress = (TextView) convertView.findViewById(R.id.textShowPercProgress);
				viewHolder.summaryName = (TextView) convertView.findViewById(R.id.homestayName);
				viewHolder.gotoDetail = (ImageView) convertView.findViewById(R.id.button1);
			}else{
				convertView.setTag(viewHolder);
			}
			temp = evaluateList.get(position);
			viewHolder.summaryName.setText(temp.getSumName());
			//Mock set Text and color
			viewHolder.textShowPercProgress.setText(NumberUtils.round(temp.getProgress(),2)+" % ");
			if(temp.getHouseId()==0){
			viewHolder.textShowPercProgress.setTextColor(temp.getProgress()>56.25 ? Color.GREEN :Color.RED);
			}else{
				viewHolder.textShowPercProgress.setTextColor(temp.getProgress()>18.75 ? Color.GREEN :Color.RED);	
			}
			viewHolder.gotoDetail.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					switchFragment(new EvaluateDetailFragment(_sm,temp.getHomStayId(),temp.getHouseId()));
				}
			});
			
			return convertView;			
		}
    	
    }
    public class ViewHolder{
    	public TextView summaryName,textShowPercProgress;
    	public ImageView gotoDetail;
    }
    public class InitAndLoadSubList extends AsyncTask<String, Void, List<TempSummary>> implements OnCancelListener{
		ProgressHUD mProgressHUD;
		public InitAndLoadSubList(){
			
		}
		
    	@Override
    	protected void onPreExecute() {
        	mProgressHUD = ProgressHUD.show(getActivity(),"Loading Content...", true,true,this);
    		super.onPreExecute();
    	}
		@Override
		protected List<TempSummary> doInBackground(String... params) {
			double score = 0.0;
			double houseScore = 0.0;
			
			List<TempSummary> result = new ArrayList<TempSummary>();
			TempSummary temp = new TempSummary();
			HomestayVO homestayVO = Entity.query(HomestayVO.class).where("type").eq(GlobalVariable.TYPE_HOMESTAY).execute();
			temp.setSumName(getActivity().getString(R.string.homestay_text)+" "+homestayInfoVO.name);
			temp.setProgress(NumberUtils.round(calculateScore(homestayVO, homestayInfoVO.id+"","0"), 2));
			score += NumberUtils.round(calculateScore(homestayVO, homestayInfoVO.id+"","0"), 2);
			temp.setHomStayId(homestayInfoVO.id);
			temp.setHouseId(0);
			if(NumberUtils.round(calculateScore(homestayVO, homestayInfoVO.id+"","0"), 2)<56.25){
				con2Err++;
			}
			result.add(temp);
			List<HouseInfoVO> houseList = homestayInfoVO.houses();
			if(houseList!=null && houseList.size()>0){
				HomestayVO housetayVO = Entity.query(HomestayVO.class).where("type").eq(GlobalVariable.TYPE_HOUSE).execute();
				for(HouseInfoVO h : houseList){
					double hScore = calculateScore(housetayVO,homestayInfoVO.id+"", h.id+"");
					TempSummary t = new TempSummary();
					t.setSumName(h.name);
					t.setProgress(NumberUtils.round(hScore, 2));
					t.setHomStayId(homestayInfoVO.id);
					t.setHouseId(h.id);
					houseScore += hScore;
					if(hScore<18.75){
						con1Err++;
					}
					result.add(t);
				}
				score += (houseScore/houseList.size());
			}
			overall =  NumberUtils.round(score,2);
		
			return result;
		}
		
		@Override
		protected void onPostExecute(List<TempSummary> result) {
			super.onPostExecute(result);
			if (result != null) {
				AllEvaluateMenuAdapter adapter = new AllEvaluateMenuAdapter(result);
				evaluateListView.setAdapter(adapter);			   
				mProgressHUD.dismiss();
			} else {
				mProgressHUD.dismiss();
			}
			String resultTxt = "";
			overAllScore.setTextColor(Color.RED);
			resultStr.setTextColor(Color.RED);
			if(homestayInfoVO.houses()==null || homestayInfoVO.houses().size()<3){
				resultTxt = getString(R.string.homestay_summary_condition1);
			}else{
				if(con1Err>0){
				resultTxt = getString(R.string.homestay_summary_condition1);	
				}else{
					if(con2Err>0){
						resultTxt = getString(R.string.homestay_summary_condition2);	
					}else{
						resultTxt = getString(R.string.homestay_summary_pass);
						overAllScore.setTextColor(Color.GREEN);
						resultStr.setTextColor(Color.GREEN);
					}
				}
			}
			resultStr.setText(resultTxt);
			overAllScore.setText(overall+" % ");
			
		}
		@Override
		public void onCancel(DialogInterface dialog) {
			// TODO Auto-generated method stub
			mProgressHUD.dismiss();
		}
	}
    public class TempSummary{
    	public String  sumName;
    	public double progress;
    	public int homStayId;
    	public int houseId;
    	
		public String getSumName() {
			return sumName;
		}
		public void setSumName(String sumName) {
			this.sumName = sumName;
		}
		public double getProgress() {
			return progress;
		}
		public void setProgress(double progress) {
			this.progress = progress;
		}
		public int getHomStayId() {
			return homStayId;
		}
		public void setHomStayId(int homStayId) {
			this.homStayId = homStayId;
		}
		public int getHouseId() {
			return houseId;
		}
		public void setHouseId(int houseId) {
			this.houseId = houseId;
		}
		
    	
    }
	private void switchFragment(Fragment fragment) {
		if (getActivity() == null)
			return;

		if (getActivity() instanceof HomeStayMainActivity) {
			HomeStayMainActivity fca = (HomeStayMainActivity) getActivity();
			fca.switchContent(fragment);
		}
	}
	
	public double calculateScore(HomestayVO homestayVO,String homeStayId,String houseId){
		double result = 0.0;
		List<CategoryVO> catList = homestayVO.categories();
		if(catList!=null && catList.size()>0){
			for(CategoryVO cat : catList){
				if("1".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*5;
				}
				else if("2".equals(cat.no)){
					result += calculateHouseFormula(cat, homeStayId, houseId)*10;
				}else if("3".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*20;
				}else if("4".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*15;
				}else if("5".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*5;
				}else if("6".equals(cat.no)){
					result += calculateHouseFormula(cat, homeStayId, houseId)*15;
				}else if("7".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*10;
				}else if("8".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*10;
				}else if("9".equals(cat.no)){
					result += calculateFormula(cat, homeStayId)*10;
				}
				
			}
		}
		
		return result;
	}
	public double calculateFormula(CategoryVO cat,String homeStayId){
		double result =0.0;
		double indCount = 0;
		double y = 0;
		double na = 0;
		List<SubCategoryVO> subList = cat.subCategories();
		if(subList!=null && subList.size()>0){
			for(SubCategoryVO sub : subList){
				List<IndicatorVO> indList = sub.indicators();
				if(indList!=null && indList.size()>0){
					indCount += indList.size();
				}
			}
			List<IndicatorResultVO> indResultList = Entity.query(IndicatorResultVO.class).where("categoryId").eq(cat.id)
					.and("homeId").eq(homeStayId).executeMulti();
			if(indResultList!=null && indResultList.size()>0){
				for(IndicatorResultVO resultVO : indResultList){
					if("0".equals(resultVO.result)){
						y++;
					}else if("2".equals(resultVO.result)){
						na++;
					}
					
				}
				
			}
			result = y/(indCount-na);
		}
		
		return result;
	}
	public double calculateHouseFormula(CategoryVO cat,String homeStayId,String houseId){
		double result =0.0;
		double indCount = 0;
		double y = 0;
		double na = 0;
		List<SubCategoryVO> subList = cat.subCategories();
		if(subList!=null && subList.size()>0){
			for(SubCategoryVO sub : subList){
				List<IndicatorVO> indList = sub.indicators();
				if(indList!=null && indList.size()>0){
					indCount += indList.size();
				}
			}
			List<IndicatorResultVO> indResultList = Entity.query(IndicatorResultVO.class).where("categoryId").eq(cat.id)
					.and("homeId").eq(homeStayId).and("houseId").eq(houseId).executeMulti();
			if(indResultList!=null && indResultList.size()>0){
				for(IndicatorResultVO resultVO : indResultList){
					if("0".equals(resultVO.result)){
						y++;
					}else if("2".equals(resultVO.result)){
						na++;
					}
					
				}
				
			}
			result = y/(indCount-na);
		}
		
		return result;
	}
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}
	public void actionSending(){
		boolean isPass = JSONParserForGetList.getInstance().postResult(homestayInfoVO.id,getActivity());
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage(isPass?getString(R.string.homestay_sync_pass):getString(R.string.homestay_sync_fail))
		       .setCancelable(false)
		       .setNegativeButton(getResources().getString(R.string.homestay_sync_ok), new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.dismiss();
						
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
		if(isPass){
			homestayInfoVO.status = "SC";
			homestayInfoVO.save();
			switchFragment(new ViewAllEvaluatePageFragment(_sm));
		}
	}

}
